{% extends "base.html" %}

{% block title %}仪表盘{% endblock %}

{% block breadcrumb %}舆情信息总览{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@3.35.0/dist/apexcharts.min.css">
<style>
    .icon-bg {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
    }
    
    .icon-bg.comments {
        background-color: rgba(52, 152, 219, 0.1);
    }
    
    .icon-bg.visits {
        background-color: rgba(46, 204, 113, 0.1);
    }
    
    .icon-bg.users {
        background-color: rgba(241, 196, 15, 0.1);
    }
    
    .icon-bg.alerts {
        background-color: rgba(231, 76, 60, 0.1);
    }
    
    .icon-bg i {
        font-size: 24px;
    }
    
    .icon-bg.comments i {
        color: var(--primary-color);
    }
    
    .icon-bg.visits i {
        color: var(--success-color);
    }
    
    .icon-bg.users i {
        color: var(--warning-color);
    }
    
    .icon-bg.alerts i {
        color: var(--danger-color);
    }
    
    .stat-card {
        display: flex;
        align-items: center;
    }
    
    .stat-info {
        flex: 1;
    }
    
    .chart-container {
        height: 350px;
        margin-bottom: 24px;
    }
    
    .sentiment-distribution {
        display: flex;
        margin-top: 16px;
        gap: 16px;
    }
    
    .sentiment-item {
        flex: 1;
        padding: 12px;
        border-radius: 8px;
        text-align: center;
    }
    
    .sentiment-item.positive {
        background-color: rgba(46, 204, 113, 0.1);
        color: var(--success-color);
    }
    
    .sentiment-item.neutral {
        background-color: rgba(241, 196, 15, 0.1);
        color: var(--warning-color);
    }
    
    .sentiment-item.negative {
        background-color: rgba(231, 76, 60, 0.1);
        color: var(--danger-color);
    }
    
    .sentiment-value {
        font-size: 24px;
        font-weight: 600;
        margin: 8px 0;
    }
    
    .keyword-cloud {
        height: 250px;
        margin-top: 16px;
    }
    
    .topic-item {
        transition: all 0.3s;
    }
    
    .topic-item:hover {
        background-color: rgba(52, 152, 219, 0.05);
        transform: translateX(5px);
    }
    
    .topic-item .title {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .metrics {
        display: flex;
        gap: 12px;
        color: var(--text-secondary);
        font-size: 13px;
    }
    
    .metrics .pv {
        display: flex;
        align-items: center;
    }
    
    .metrics .pv::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: var(--primary-color);
        margin-right: 4px;
    }
    
    .metrics .percentage {
        display: flex;
        align-items: center;
    }
    
    .metrics .percentage::before {
        content: '';
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background-color: var(--success-color);
        margin-right: 4px;
    }
    
    .date-filter {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 24px;
    }
    
    .date-filter select {
        padding: 8px 12px;
        border-radius: 4px;
        border: 1px solid var(--border-color);
        background-color: white;
        font-size: 14px;
    }
    
    .refresh-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background-color: var(--primary-color);
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s;
    }
    
    .refresh-btn:hover {
        background-color: #2980b9;
    }
    
    .source-distribution {
        margin-top: 16px;
    }
</style>
{% endblock %}

{% block content %}
<!-- 日期筛选 -->
<div class="date-filter">
    <select id="timeRange" data-tooltip="选择时间范围">
        <option value="7">最近7天</option>
        <option value="30" selected>最近30天</option>
        <option value="90">最近90天</option>
    </select>
    <button id="refreshBtn" class="refresh-btn" data-tooltip="刷新数据">
        <i class="material-icons">refresh</i>
        刷新数据
    </button>
</div>

<!-- 数据概览卡片 -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="icon-bg comments">
            <i class="material-icons">comment</i>
        </div>
        <div class="stat-info">
            <div class="stat-header">
                <h3>评论总数</h3>
                <div class="trend up">
                    <span>15%</span>
                    <i class="material-icons">trending_up</i>
                </div>
            </div>
            <div class="value">395,000</div>
            <div class="subtitle">日同比</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon-bg visits">
            <i class="material-icons">visibility</i>
        </div>
        <div class="stat-info">
            <div class="stat-header">
                <h3>访问量</h3>
                <div class="trend up">
                    <span>25%</span>
                    <i class="material-icons">trending_up</i>
                </div>
            </div>
            <div class="value">25,450</div>
            <div class="subtitle">日同比</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon-bg users">
            <i class="material-icons">people</i>
        </div>
        <div class="stat-info">
            <div class="stat-header">
                <h3>用户量</h3>
                <div class="trend neutral">
                    <span>30</span>
                    <i class="material-icons">trending_flat</i>
                </div>
            </div>
            <div class="value">13,256</div>
            <div class="subtitle">月增长</div>
        </div>
    </div>
    <div class="stat-card">
        <div class="icon-bg alerts">
            <i class="material-icons">warning</i>
        </div>
        <div class="stat-info">
            <div class="stat-header">
                <h3>预警数量</h3>
                <div class="trend down">
                    <span>25%</span>
                    <i class="material-icons">trending_down</i>
                </div>
            </div>
            <div class="value">35</div>
            <div class="subtitle">日同比</div>
        </div>
    </div>
</div>

<!-- 图表区域 -->
<div class="chart-container">
    <div class="card-header">
        <h3>舆情声量趋势</h3>
        <div class="card-tools">
            <button class="btn-icon" id="downloadTrendChart" data-tooltip="下载图表">
                <i class="material-icons">file_download</i>
            </button>
            <button class="btn-icon" data-tooltip="更多选项">
                <i class="material-icons">more_vert</i>
            </button>
        </div>
    </div>
    <div id="trendChart" style="position: relative;">
        <div class="loading-overlay" id="trendChartLoading" style="display: none;">
            <div class="loading"></div>
        </div>
    </div>
</div>

<!-- 情感分析和热门话题 -->
<div class="content-grid">
    <div class="hot-topics">
        <div class="card-header">
            <h3>情感分析</h3>
            <div class="card-tools">
                <button class="btn-icon" data-tooltip="刷新数据">
                    <i class="material-icons">refresh</i>
                </button>
                <button class="btn-icon" data-tooltip="更多选项">
                    <i class="material-icons">more_vert</i>
                </button>
            </div>
        </div>
        <div id="sentimentChart" style="position: relative;">
            <div class="loading-overlay" id="sentimentChartLoading" style="display: none;">
                <div class="loading"></div>
            </div>
        </div>
        <div class="sentiment-distribution">
            <div class="sentiment-item positive">
                <div>正面</div>
                <div class="sentiment-value">65%</div>
                <div>256,750</div>
            </div>
            <div class="sentiment-item neutral">
                <div>中性</div>
                <div class="sentiment-value">20%</div>
                <div>79,000</div>
            </div>
            <div class="sentiment-item negative">
                <div>负面</div>
                <div class="sentiment-value">15%</div>
                <div>59,250</div>
            </div>
        </div>
    </div>
    <div class="hot-topics">
        <div class="card-header">
            <h3>热门话题</h3>
            <div class="card-tools">
                <button class="btn-icon">
                    <i class="material-icons">refresh</i>
                </button>
                <button class="btn-icon">
                    <i class="material-icons">more_vert</i>
                </button>
            </div>
        </div>
        <div class="topics-list">
            <div class="topic-item">
                <div class="rank">1</div>
                <div class="topic-content">
                    <div class="title">港立香港通缉长达年度内党员建议修改刑期长达下不治内内事</div>
                    <div class="metrics">
                        <span class="pv">浏览量: 500</span>
                        <span class="percentage">增长率: 28%</span>
                    </div>
                </div>
            </div>
            <div class="topic-item">
                <div class="rank">2</div>
                <div class="topic-content">
                    <div class="title">国内经济发展新趋势分析报告发布</div>
                    <div class="metrics">
                        <span class="pv">浏览量: 485</span>
                        <span class="percentage">增长率: 24%</span>
                    </div>
                </div>
            </div>
            <div class="topic-item">
                <div class="rank">3</div>
                <div class="topic-content">
                    <div class="title">新能源汽车产业链上下游协同发展</div>
                    <div class="metrics">
                        <span class="pv">浏览量: 432</span>
                        <span class="percentage">增长率: 22%</span>
                    </div>
                </div>
            </div>
            <div class="topic-item">
                <div class="rank">4</div>
                <div class="topic-content">
                    <div class="title">人工智能技术在医疗领域的应用与挑战</div>
                    <div class="metrics">
                        <span class="pv">浏览量: 398</span>
                        <span class="percentage">增长率: 19%</span>
                    </div>
                </div>
            </div>
            <div class="topic-item">
                <div class="rank">5</div>
                <div class="topic-content">
                    <div class="title">全球气候变化对农业生产的影响研究</div>
                    <div class="metrics">
                        <span class="pv">浏览量: 376</span>
                        <span class="percentage">增长率: 17%</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 关键词云和地图 -->
<div class="content-grid" style="margin-top: 24px;">
    <div class="hot-topics">
        <div class="card-header">
            <h3>热门关键词</h3>
            <div class="card-tools">
                <button class="btn-icon">
                    <i class="material-icons">refresh</i>
                </button>
                <button class="btn-icon">
                    <i class="material-icons">more_vert</i>
                </button>
            </div>
        </div>
        <div id="keywordCloud" class="keyword-cloud"></div>
        <div class="source-distribution">
            <div class="card-header" style="margin-bottom: 10px;">
                <h4>来源分布</h4>
            </div>
            <div id="sourceChart"></div>
        </div>
    </div>
    <div class="map-card">
        <div class="card-header">
            <h3>地域分布</h3>
            <div class="card-tools">
                <button class="btn-icon">
                    <i class="material-icons">fullscreen</i>
                </button>
                <button class="btn-icon">
                    <i class="material-icons">more_vert</i>
                </button>
            </div>
        </div>
        <div id="chinaMap"></div>
    </div>
</div>
{% endblock %}

{% block scripts %}

<!-- 确保按照这个顺序引入 -->
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/map/js/china.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud@2.0.0/dist/echarts-wordcloud.min.js"></script>
<!-- 先引入 mock 数据 -->
<script src="{{ url_for('static', filename='js/mock.js') }}"></script>
<!-- 最后引入初始化代码 -->
<script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/map/js/china.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts@3.35.0/dist/apexcharts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud@2.0.0/dist/echarts-wordcloud.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 显示加载状态
        function showLoading(chartId) {
            document.getElementById(chartId + 'Loading').style.display = 'flex';
        }
        
        // 隐藏加载状态
        function hideLoading(chartId) {
            document.getElementById(chartId + 'Loading').style.display = 'none';
        }
        
        // 模拟数据加载
        function simulateLoading(chartId, callback, delay = 1000) {
            showLoading(chartId);
            setTimeout(() => {
                hideLoading(chartId);
                if (callback) callback();
            }, delay);
        }
        
        // 全局变量存储图表实例
        let trendChart, sentimentChart, keywordChart, sourceChart, mapChart;
        let dashboardData = null;
        
        // 从API获取数据
        function fetchDashboardData(days = 30) {
            // 显示所有图表的加载状态
            showLoading('trendChart');
            showLoading('sentimentChart');
            
            // 获取数据
            fetch(`/api/dashboard/data?days=${days}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    dashboardData = data;
                    updateDashboard(data);
                })
                .catch(error => {
                    console.error('获取数据失败:', error);
                    // 使用模拟数据
                    if (window.mockData && window.mockData.dashboard) {
                        console.log('使用模拟数据');
                        dashboardData = window.mockData.dashboard;
                        updateDashboard(window.mockData.dashboard);
                    } else {
                        alert('获取数据失败，请稍后再试');
                    }
                    
                    // 隐藏加载状态
                    hideLoading('trendChart');
                    hideLoading('sentimentChart');
                });
        }
        
        // 更新仪表板上的所有图表和数据
        function updateDashboard(data) {
            // 更新统计卡片
            updateStats(data.stats);
            
            // 更新趋势图
            updateTrendChart(data.dates, data.trend);
            
            // 更新情感分析图
            updateSentimentChart(data.sentiment);
            
            // 更新热门话题
            updateHotTopics(data.topics);
            
            // 更新关键词云
            updateKeywordCloud(data.keywords);
            
            // 更新来源分布
            updateSourceChart(data.sources);
            
            // 更新地区分布
            updateMapChart(data.regions);
        }
        
        // 更新统计卡片
        function updateStats(stats) {
            document.getElementById('totalComments').textContent = stats.total_comments.toLocaleString();
            document.getElementById('totalVisits').textContent = stats.total_visits.toLocaleString();
            document.getElementById('userCount').textContent = stats.user_count.toLocaleString();
            document.getElementById('alertCount').textContent = stats.alert_count.toLocaleString();
        }
        
        // 更新趋势图
        function updateTrendChart(dates, trendData) {
            const options = {
                series: [{
                    name: '总量',
                    data: trendData.total
                }, {
                    name: '正面',
                    data: trendData.positive
                }, {
                    name: '负面',
                    data: trendData.negative
                }],
                chart: {
                    height: 300,
                    type: 'area',
                    toolbar: {
                        show: true
                    }
                },
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    curve: 'smooth'
                },
                colors: ['#3498db', '#2ecc71', '#e74c3c'],
                fill: {
                    type: 'gradient',
                    gradient: {
                        shadeIntensity: 1,
                        opacityFrom: 0.7,
                        opacityTo: 0.3,
                        stops: [0, 90, 100]
                    }
                },
                xaxis: {
                    categories: dates
                },
                tooltip: {
                    x: {
                        format: 'dd/MM/yy'
                    },
                }
            };
            
            if (trendChart) {
                trendChart.updateOptions(options);
            } else {
                trendChart = new ApexCharts(document.querySelector("#trendChart"), options);
                trendChart.render();
            }
            
            hideLoading('trendChart');
        }
        
        // 更新情感分析图
        function updateSentimentChart(sentimentData) {
            const option = {
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    orient: 'horizontal',
                    bottom: 'bottom'
                },
                series: [
                    {
                        name: '情感分析',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '18',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: [
                            { value: sentimentData.positive, name: '正面', itemStyle: { color: '#2ecc71' } },
                            { value: sentimentData.neutral, name: '中性', itemStyle: { color: '#f1c40f' } },
                            { value: sentimentData.negative, name: '负面', itemStyle: { color: '#e74c3c' } }
                        ]
                    }
                ]
            };
            
            if (!sentimentChart) {
                sentimentChart = echarts.init(document.getElementById('sentimentChart'));
            }
            sentimentChart.setOption(option);
            hideLoading('sentimentChart');
            
            // 更新情感分布数据
            const total = sentimentData.positive + sentimentData.neutral + sentimentData.negative;
            document.querySelector('.sentiment-item.positive .sentiment-value').textContent = 
                Math.round(sentimentData.positive / total * 100) + '%';
            document.querySelector('.sentiment-item.positive').lastElementChild.textContent = 
                sentimentData.positive.toLocaleString();
                
            document.querySelector('.sentiment-item.neutral .sentiment-value').textContent = 
                Math.round(sentimentData.neutral / total * 100) + '%';
            document.querySelector('.sentiment-item.neutral').lastElementChild.textContent = 
                sentimentData.neutral.toLocaleString();
                
            document.querySelector('.sentiment-item.negative .sentiment-value').textContent = 
                Math.round(sentimentData.negative / total * 100) + '%';
            document.querySelector('.sentiment-item.negative').lastElementChild.textContent = 
                sentimentData.negative.toLocaleString();
        }
        
        // 更新热门话题
        function updateHotTopics(topics) {
            const topicsContainer = document.querySelector('.topics-list');
            topicsContainer.innerHTML = '';
            
            topics.forEach((topic, index) => {
                const sentimentClass = topic.sentiment === 'positive' ? 'positive' : 
                                      (topic.sentiment === 'negative' ? 'negative' : 'neutral');
                
                const topicItem = document.createElement('div');
                topicItem.className = 'topic-item';
                topicItem.innerHTML = `
                    <div class="rank">${index + 1}</div>
                    <div class="topic-content">
                        <div class="title">${topic.title}</div>
                        <div class="metrics">
                            <span class="pv">热度: ${topic.hot}</span>
                            <span class="percentage">情感: ${topic.sentiment}</span>
                        </div>
                    </div>
                `;
                
                topicItem.addEventListener('click', function() {
                    alert(`您点击了话题: ${topic.title}`);
                });
                
                topicsContainer.appendChild(topicItem);
            });
        }
        
        // 更新关键词云
        function updateKeywordCloud(keywords) {
            const option = {
                series: [{
                    type: 'wordCloud',
                    shape: 'circle',
                    left: 'center',
                    top: 'center',
                    width: '100%',
                    height: '100%',
                    right: null,
                    bottom: null,
                    sizeRange: [12, 30],
                    rotationRange: [-90, 90],
                    rotationStep: 45,
                    gridSize: 8,
                    drawOutOfBound: false,
                    textStyle: {
                        fontFamily: 'sans-serif',
                        fontWeight: 'bold',
                        color: function () {
                            return 'rgb(' + [
                                Math.round(Math.random() * 160),
                                Math.round(Math.random() * 160),
                                Math.round(Math.random() * 160)
                            ].join(',') + ')';
                        }
                    },
                    emphasis: {
                        focus: 'self',
                        textStyle: {
                            shadowBlur: 10,
                            shadowColor: '#333'
                        }
                    },
                    data: keywords
                }]
            };
            
            if (!keywordChart) {
                keywordChart = echarts.init(document.getElementById('keywordCloud'));
            }
            keywordChart.setOption(option);
        }
        
        // 更新来源分布图表
        function updateSourceChart(sources) {
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    show: false
                },
                series: [
                    {
                        name: '来源分布',
                        type: 'pie',
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: true,
                            position: 'outside',
                            formatter: '{b}: {d}%'
                        },
                        labelLine: {
                            show: true
                        },
                        data: sources
                    }
                ]
            };
            
            if (!sourceChart) {
                sourceChart = echarts.init(document.getElementById('sourceChart'));
            }
            sourceChart.setOption(option);
        }
        
        // 更新中国地图
        function updateMapChart(regions) {
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}<br/>舆情量: {c}'
                },
                visualMap: {
                    min: 0,
                    max: 1000,
                    text: ['高', '低'],
                    realtime: false,
                    calculable: true,
                    inRange: {
                        color: ['#e0f3f8', '#2171b5']
                    }
                },
                series: [{
                    name: '舆情分布',
                    type: 'map',
                    map: 'china',
                    itemStyle: {
                        normal: {
                            borderColor: '#fff',
                            areaColor: '#eee'
                        }
                    },
                    emphasis: {
                        itemStyle: {
                            areaColor: '#3498db'
                        },
                        label: {
                            show: true
                        }
                    },
                    data: regions
                }]
            };
            
            if (!mapChart) {
                mapChart = echarts.init(document.getElementById('chinaMap'));
            }
            mapChart.setOption(option);
        }
        
        // 初始化仪表板
        fetchDashboardData();
        
        // 窗口大小变化时重新调整图表大小
        window.addEventListener('resize', function() {
            if (keywordChart) keywordChart.resize();
            if (sourceChart) sourceChart.resize();
            if (mapChart) mapChart.resize();
            if (sentimentChart) sentimentChart.resize();
        });
        
        // 日期筛选和刷新按钮
        document.getElementById('refreshBtn').addEventListener('click', function() {
            const days = document.getElementById('timeRange').value;
            console.log('刷新数据，时间范围：', days, '天');
            
            // 从API获取新数据
            fetchDashboardData(days);
            
            // 添加刷新按钮动画
            this.classList.add('refreshing');
            setTimeout(() => {
                this.classList.remove('refreshing');
            }, 1000);
        });
        
        // 为下载按钮添加事件
        document.getElementById('downloadTrendChart').addEventListener('click', function() {
            if (trendChart) {
                trendChart.dataURI().then(({ imgURI }) => {
                    const downloadLink = document.createElement('a');
                    downloadLink.href = imgURI;
                    downloadLink.download = '趋势图.png';
                    document.body.appendChild(downloadLink);
                    downloadLink.click();
                    document.body.removeChild(downloadLink);
                });
            } else {
                alert('图表尚未加载完成');
            }
        });
    });
</script>
{% endblock %} 